package br.com.midiaseducativas.tutor.jogos.associativegame {
	import br.com.midiaseducativas.tutor.events.FeedBackEvent;
	import br.com.midiaseducativas.tutor.events.SpeechEvent;
	import br.com.midiaseducativas.tutor.jogos.associativegame.events.CardEvent;
	import br.com.midiaseducativas.tutor.jogos.associativegame.vo.CardVO;
	
	import com.demonsters.debugger.MonsterDebugger;
	import com.greensock.TweenLite;
	
	import flash.display.LoaderInfo;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.geom.ColorTransform;
	import flash.geom.Point;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	/**
	 * Owner: Caio
	 * Date: Apr 14, 2011
	 */
	
	
	public class GameCore extends EventDispatcher {
		
		private var xmlLoader:URLLoader;
		private var gameConfigXML:XML;
		private var cardVOList:Array;
		
		private var cardStage:CardStage;
		
		private var leftListCard:Array;
		private var rigthListCard:Array;
		
		private var watingCard:Card;
		
		private var matchCount:uint;
		
		private var rightColumn:Array;
		private var leftColumn:Array;
		
		private var time:Number;
		private var timer:Timer;
		
		

		
		
		public function GameCore(pCardStage:CardStage, pXMLString:String) {
			//MonsterDebugger.trace(this, this.loadInfo.parameters.xml);
			try {
				this.xmlLoader = new URLLoader();
				this.xmlLoader.addEventListener(Event.COMPLETE, onLoaderComplete);
				MonsterDebugger.trace(this, "Passou 1");
				this.xmlLoader.load(new URLRequest(pXMLString));
				MonsterDebugger.trace(this, "Passou 2");
				this.cardStage = pCardStage;
			} catch (e:Error){
				MonsterDebugger.trace(this, e);
			}
			
			this.matchCount = 0;
			
			this.time = 0;
			this.timer = new Timer(1);
			this.timer.addEventListener(TimerEvent.TIMER, onTimerTick);
			this.timer.start();
			
			this.rightColumn = [0, 1 , 2];
			this.leftColumn = [0, 1 , 2];
			
		}
		
		protected function onLoaderComplete(event:Event):void {
			
			this.gameConfigXML = new XML(this.xmlLoader.data);
			this.cardStage.title.text = this.gameConfigXML..title;
			this.getVOs();
		}
		
		/**
		 * Função que cria os vos a partir do xml
		 * @return void
		 * @author Caio
		 **/

		private function getVOs():void {
			
			this.cardVOList = new Array();
			this.leftListCard = new Array();
			this.rigthListCard = new Array();
			
			for (var index:String in this.gameConfigXML..pair) {
				
				var cardVO1:CardVO = new CardVO();
				var type1:String = this.gameConfigXML..pair[index].card[0].@type;
				cardVO1.source = (this.gameConfigXML..pair[index].card[0]).@source;
				cardVO1.idAssociation = (this.gameConfigXML..pair[index].card[0]).@idAssociation;
				cardVO1.type = type1;
				
				var cardVO2:CardVO = new CardVO();
				var type2:String = this.gameConfigXML..pair[index].card[1].@type;
				cardVO2.source = (this.gameConfigXML..pair[index].card[1]).@source;
				cardVO2.idAssociation = (this.gameConfigXML..pair[index].card[1]).@idAssociation;
				cardVO2.type = type2;
				
				cardVOList.push([cardVO1, cardVO2]);
				
			}
			
			this.sortVOs();
		}
		
		private function sortVOs():void	{
			var pos:Number;
			var tuplaArr:Array;
			for (var i:int = 0; i < 3; i++) {
				pos = Math.round((Math.random()*(this.cardVOList.length-1)));
				tuplaArr = this.cardVOList[pos];
				this.createCards(tuplaArr[0]);
				this.createCards(tuplaArr[1]);
				
				this.cardVOList.splice(pos,1);
				
			}
			
		}
		
		
		/**
		 * Função que retorna posição aleatória
		 * @return Point
		 * @author Caio Neves
		 **/

		public function randomPosition(pCard:Card):Point {
			
			var retorno:Point = new Point();
			var pos:Number;
			
			//if (Math.random() < 0.5 && this.rightColumn.length != 0) {
			if (pCard.vo.type == "img") {
				if (this.rightColumn.length != 0){
					pos = Math.round(Math.random()*(this.rightColumn.length-1));
					retorno.x = 200;
					retorno.y = 130 + (pCard.visual.height+10)*this.rightColumn[pos];
					this.rightColumn.splice(pos, 1);
				}else {
					retorno = this.randomPosition(pCard);
				}
				
			} else {
				if (this.leftColumn.length != 0){
					pos = Math.round(Math.random()*(this.leftColumn.length-1));
					retorno.x = 550;
					retorno.y = 130 + (pCard.visual.height+10)*this.leftColumn[pos];
					this.leftColumn.splice(pos, 1);
				}else {
					retorno = this.randomPosition(pCard);
				}
			}
			
			return retorno;
		}
		
		/**
		 * Function that puts the card in position
		 * @return void
		 * @author Caio Neves
		 **/

		public function createCards(pVO:CardVO):void {
			var point:Point;
			var card:Card = new Card();
			if (pVO.type == "img") {
				card.vo = pVO;
				point = this.randomPosition(card);
				card.visual.y = point.y;
				card.visual.x = point.x;
			}else {
				card.vo = pVO;
				point = this.randomPosition(card);
				card.visual.y = point.y;
				card.visual.x = point.x;
			}
			
			this.cardStage.addChild(card.visual);
			card.addEventListener(CardEvent.CLICK, onCardClick);
		}
		
		protected function onCardClick(event:CardEvent):void {
			if (this.watingCard == null){
				this.watingCard = event.card;
			} else {
				
				event.card.visual.shape.filters = [];
				this.watingCard.visual.shape.filters = [];
				MonsterDebugger.trace(this, event.card.vo.idAssociation +" - "+ this.watingCard.vo.idAssociation);
				if (event.card.vo.idAssociation != this.watingCard.vo.idAssociation){
					var eventWrong:FeedBackEvent = new FeedBackEvent(FeedBackEvent.WRONG, "Atention!", "Try Again.", true);
					eventWrong.time = this.time;
					this.dispatchEvent(eventWrong);
					this.watingCard = null;
				} else {
					trace("Deu Certo");
					var colorTransformer:ColorTransform = new ColorTransform();
					colorTransformer.color = 0x26BE2F;
					
					var speech:String;
					
					if (event.card.vo.type == "text"){
						speech = event.card.vo.source;
					} else {
						speech = this.watingCard.vo.source;
					}
					
					event.card.visual.shape.transform.colorTransform = colorTransformer;
					this.watingCard.visual.shape.transform.colorTransform = colorTransformer;
					
					//TweenLite.to(event.card.visual, 1, {transformMatrix:{rotation:360}});
					//TweenLite.to(this.watingCard.visual, 1, {transformMatrix:{rotation:360}});
					
					event.card.visual.enabled = false;
					this.watingCard.visual.enabled = false;
					
					event.card.removeClickEventListener();
					this.watingCard.removeClickEventListener();
					
					TweenLite.to(event.card.visual, 1, {rotationY:360});
					TweenLite.to(this.watingCard.visual, 1, {rotationY:360});
					
					this.matchCount += 1;
					
					
					this.watingCard = null;
					var eventRight:FeedBackEvent = new FeedBackEvent(FeedBackEvent.RIGHT, "Congratulations!", "Good Job.", true);
					eventRight.time = this.time;
					this.dispatchEvent(eventRight);
					this.dispatchEvent(new SpeechEvent(SpeechEvent.SAY, speech, true));
					var eventComplete:FeedBackEvent;
					if (this.matchCount == 3) {
						eventComplete = new FeedBackEvent(FeedBackEvent.COMPLETE, "Congratulations!", "You've done the exercise.");
						eventComplete.time = this.time;
						MonsterDebugger.trace(this, this.time);
						this.dispatchEvent(eventComplete);
						this.timer.stop();
						this.timer.removeEventListener(TimerEvent.TIMER, onTimerTick);
						this.timer = null;
					}
						
					
				}
			}
		}
		
		protected function onTimerTick(event:Event):void {
			this.time += 1;
		}
		
		
	}
}